import React, { useEffect, useState, useMemo, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { CSSTransition } from "react-transition-group";
import { isEmpty, storeOptionListMap } from '@/utils/common';
import { useDispatch, useSelector, history } from 'umi';
import { Mask, Price, Message } from '@/design';
import NumberPicker from '@/components/NumberPicker/NumberPicker';
import numeral from 'numeral';
import ReserveModal from './reserveModal';
import SeatNumModal from './seatNumModal';

import styles from './shoppingCart.less';

export default function (props: any) {
  const { shoppingVisiable, num } = props;
  const { preTimeDetail, codeDetail, storeOptionList } = useSelector((state: any) => state.store);
  const { bespeakStartTime } = useSelector((state: any) => state.order);

  const { cartList } = useSelector((state: any) => state.cartList);

  const [cartlistVisiable, setCartlistVisiable] = useState<boolean>(false);
  const [reserveVisiable, setReserveVisiable] = useState<boolean>(false);
  const [seatNumVisiable, setSeatNumVisiable] = useState<boolean>(false);

  const dispatch = useDispatch();

  // useEffect(() => {
  //   const { diningWay } = codeDetail;
  //   if (isTogoBespeak(diningWay)) {//外帶模式 需要預約時間段
  //     fetchMealTime();
  //   }
  // }, [])

  /* 計算總價格 */
  const totalNum = useMemo(() => {
    let numTotal: any = numeral(0);
    if (isEmpty(cartList)) return 0;
    console.log('=====購物車', cartList);
    cartList.forEach((item: any) => {
      let thisAmount = numeral(item.productPrice).multiply(item.productQuantity).value();
      numTotal = numeral(numTotal || 0).add(thisAmount).value();
      if (!isEmpty(item.tasteList)) {
        item.tasteList.forEach((taste: any) => {
          let thisAmount = numeral(taste.num).multiply(taste.price).value()
          numTotal = numeral(numTotal || 0).add(thisAmount).value();
        })
      }
      if (!isEmpty(item.productPackages)) {
        console.log('222', item.productPackages)
        item.productPackages.forEach((productPackage: any) => {
          if (!isEmpty(productPackage.packageDetails)) {
            productPackage.packageDetails.forEach((o: any) => {
              if (!isEmpty(o.tasteList)) {
                o.tasteList.forEach((taste: any) => {
                  let thisAmount = numeral(taste.num).multiply(taste.price).value();
                  thisAmount = numeral(thisAmount).multiply(o.quantity).value();
                  numTotal = numeral(numTotal || 0).add(thisAmount).value();
                })
              }  else {//沒有tasteList
                let thisAmount = numeral(o.adjustPrice).multiply(o.quantity).value();
                numTotal = numeral(numTotal || 0).add(thisAmount).value();
              }
            })
          }

          
        })
      }
    })

    return numTotal
  }, [cartList])

  /* 所选的菜品规格 */
  const chooseSpecs = (tasteList: any) => {
    let str: any = [];
    tasteList.forEach((o: any) => {
      str.push(`${o.tasteName}+${o.num}`)
    })
    return str.join('/')
  }

  // 
  const choosePackSpecs = (productPackages: any) => {
    console.log('productPackagesproductPackages', productPackages)
    let str: any = [];
    productPackages.forEach((o: any) => {
      o.packageDetails.forEach((taste: any) => {
        str.push(`${taste.productName}`)
        // if(!isEmpty(taste.tasteList)) {
        //   taste.tasteList.forEach((taste: any) => {
        //     str.push(`${taste.tasteName}+${taste.num}`)
        //   })
        // }
      })
    })
    return str.join('/')
  }

  /* 所选的菜品tasteIds */
  const chooseTasteIds = (tasteList: any, param: string) => {
    let str: any = [];
    tasteList.forEach((o: any) => {
      str.push(`${o[param]}`)
    })
    return str.join('_')
  }

  /* 計算價格 */
  const totaGoodlNum = (item: any) => {
    const { tasteList } = item;
    let numTotal: any = numeral(0);
    let thisAmount = numeral(item.productPrice).multiply(item.productQuantity).value();
    numTotal = numeral(numTotal || 0).add(thisAmount).value();
    if (!isEmpty(tasteList)) {
      tasteList.forEach((taste: any) => {
        let thisAmount = numeral(taste.num).multiply(taste.price).value()
        numTotal = numeral(numTotal || 0).add(thisAmount).value();
      })
    }
    if (!isEmpty(item.productPackages)) {
      item.productPackages.forEach((productPackage: any) => {
        if (!isEmpty(productPackage.packageDetails)) {
          productPackage.packageDetails.forEach((o: any) => {
            if (!isEmpty(o.tasteList)) {
              o.tasteList.forEach((taste: any) => {
                let thisAmount = numeral(taste.num).multiply(taste.price).value();
                thisAmount = numeral(thisAmount).multiply(o.quantity).value();
                numTotal = numeral(numTotal || 0).add(thisAmount).value();
              })
            }  else {//沒有tasteList
              let thisAmount = numeral(o.adjustPrice).multiply(o.quantity).value();
              numTotal = numeral(numTotal || 0).add(thisAmount).value();
            }
          })
        }
      })
    }
    return numTotal
  }

  const handleNumChange = (num: number, curSpec: any) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let newCurSpec = JSON.parse(JSON.stringify(curSpec));
    let curTasteItemIds = chooseTasteIds(curSpec.tasteList, 'tasteItemId');
    let curTasteNums = chooseTasteIds(curSpec.tasteList, 'num');

    const { productId } = curSpec;
    if (num === 0) {//要删除这个商品
      newCartList = newCartList.filter((item: any) => {
        let tasteItemIds = chooseTasteIds(item.tasteList, 'tasteItemId');
        let tasteNums = chooseTasteIds(item.tasteList, 'num');
        if (`${item.productId}_${tasteItemIds}_${tasteNums}` !== `${newCurSpec.productId}_${curTasteItemIds}_${curTasteNums}`) {
          return item
        }
      })
    }
    newCartList = newCartList.map((item: any) => {
      let tasteItemIds = chooseTasteIds(item.tasteList, 'tasteItemId');
      let tasteNums = chooseTasteIds(item.tasteList, 'num');
      if (`${item.productId}_${tasteItemIds}_${tasteNums}` === `${newCurSpec.productId}_${curTasteItemIds}_${curTasteNums}`) {//是當前點擊的商品 商品數量減1
        return {
          ...item,
          productQuantity: num
        }
      }
      return item
    })
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
    if (newCartList.length === 0) {
      setCartlistVisiable(false)
    }
  }

  const handleClear = () => {
    dispatch({
      type: 'cartList/clearCartList',
      payload: []
    })
    setCartlistVisiable(false)
  }

  const hours = () => {
    const { timeList } = preTimeDetail;
    let hours: Array<any> = [];
    if (!isEmpty(timeList)) {
      timeList.forEach((item: any) => {
        hours.push(item.hour)
      })
    }
    return hours
  }

  // const hours = useMemo(() => {
  //   const { timeList } = preTimeDetail;
  //   let hours: Array<any> = [];
  //   if(!isEmpty(timeList)) {
  //     timeList.forEach((item:any) => {
  //       hours.push(item.hour)
  //     })
  //   }
  // }, [preTimeDetail])

  //是否是預約外賣
  const isTogoBespeak = (diningWay: string) => {
    return diningWay === 'togoBespeak'
  }

  // 是否是堂食
  const isDiningRoom = (diningWay: string) => {
    return diningWay === 'diningroom'
  }

  /* 查詢预约时间段详情 */
  const fetchPretimeDetail = () => {
    dispatch({
      type: 'store/fetchPreTime'
    })
  }

  // const fetchMealTime = () => {
  //   console.log('傳入', codeDetail);
  //   dispatch({
  //     type: 'store/fetchMealTime',
  //     payload: {
  //       braId: currentstore.braId
  //     }
  //   })
  // }

const clearBespeakStartTime = () => {
  dispatch({
    type: 'order/saveBespeakStartTime',
    paylaod: ''
  })
}

  /** 預約時間 */
  const handleChoosePreTime = () => {
    const { diningWay, togoBespeak } = codeDetail;
    // console.log('可以預約的時間段是', preTimeDetail);
    // console.log('storeOptionListMap().get(', storeOptionListMap().get('people_number_control'));
    // console.log('codeDetailcodeDetail', codeDetail)
    if (diningWay === 'togoBespeak') { //是否是預約
      clearBespeakStartTime();
      return setReserveVisiable(true);
    }
    if (storeOptionListMap(storeOptionList).get('people_number_control') === '1') {//是否需要选人数
      return setSeatNumVisiable(true)
    }

    return history.push('/checkorder')

    // history.push('/checkorder')

    // if(isTogoBespeak(diningWay)) {
    //   setReserveVisiable(true);
    // }

    // setSeatNumVisiable(true);
    // if(isDiningRoom(diningWay)) {
    //   setSeatNumVisiable(true)
    // }

    // if(isTakeOut(diningWay)) {//外帶模式 需要預約時間段
    //   fetchPretimeDetail();
    //   const { timeList } = preTimeDetail;
    //   if(!isEmpty(timeList)) {
    //     DatePicker.time({
    //       defaultValue:  `${hours()[0]}:${timeList[0].minutes[0]}`,
    //       hours: hours(),
    //       timeList,
    //       onSelect: (birthday) => {
    //         console.log('選好了預約時間', birthday)
    //       }
    //     })
    //   }
    // }

  }

  const handleToCheckOrder = () => {
    if(isEmpty(bespeakStartTime)) {
     return Message.error('請選擇預約時間')
    }
    history.push('/checkorder')
  }

  let result = (<>
    {shoppingVisiable ? <div className={styles.shopping_wrap}>
      <button className={styles.cart_total} onClick={() => setCartlistVisiable(!cartlistVisiable)}>
        <span className={styles.badge}>{num}</span>
        <span className={styles.cart_icon}></span>
        <span>共 <Price price={totalNum} /></span>
      </button>
      <button className={styles.choose_ok} onClick={handleChoosePreTime}>選好了</button>
    </div> : null}
    {cartlistVisiable && <Mask onClick={() => setCartlistVisiable(!cartlistVisiable)} />}
    <CSSTransition
      unmountOnExit
      classNames="spec_foot_modal"
      timeout={300}
      in={cartlistVisiable}
    >
      <div className={styles.cartlist_wrap}>
        <div className={styles.cart_top}>
          <div>點餐單</div>
          <div onClick={handleClear}>清空</div>
        </div>
        <div className={styles.list}>
          {cartList.map((item: any, index: number) => {
            return (<div className={styles.cart_item} key={`${item.categoryId}_${item.productId}_${index}`}>
              <div className={styles.spec}>
                <p>{item.productName}</p>
                <p>{isEmpty(item.productPackages) ? chooseSpecs(item.tasteList) : choosePackSpecs(item.productPackages)}</p>
              </div>
              <div>
                <p className={styles.price}><Price price={totaGoodlNum(item)}></Price></p>
                <NumberPicker value={item.productQuantity} attr={item} onChange={handleNumChange} />
              </div>
            </div>)
          })}
        </div>
        {/* <DatePicker></DatePicker> */}
      </div>
    </CSSTransition>
    <ReserveModal reserveVisiable={reserveVisiable} onClose={() => setReserveVisiable(false)} onClickSure={handleToCheckOrder} />
    <SeatNumModal seatNumVisiable={seatNumVisiable} onClose={() => setSeatNumVisiable(false)} onClickSure={handleToCheckOrder} />
  </>
  )
  return result
  // return ReactDOM.createPortal(result, document.body);
}